package com.fotkidemo;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.*;
import android.widget.AdapterView;
import android.widget.Toast;
import com.fotkidemo.beans.Album;
import com.fotkidemo.beans.Image;
import com.fotkidemo.network.json.AbstractJsonEntryParser;
import com.fotkidemo.network.json.JsonImagesParser;
import com.fotkidemo.tasks.DownloadAndParseEntryTask;
import com.fotkidemo.tasks.LoadTask;
import com.fotkidemo.tasks.OnTaskCompleteListener;
import com.fotkidemo.tasks.TaskManager;

import java.io.File;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: roma
 * Date: 6/24/12
 * Time: 11:51 AM
 * To change this template use File | Settings | File Templates.
 */

//Загрузка набора фото из определенного удаленного альбома на sd-card
public class AlbumsLoadActivity extends FragmentActivity implements AlbumsFragment.OnAlbumsClickListener, OnTaskCompleteListener {
    private static final String TAG = "AlbumsFragment";
    public static final String EXTRA_URL = "extra_url";

    public static final int MENU_LOAD_ALL = 101;
    public static final int MENU_LOAD_ONE_BY_ONE = 102;

    private String dir = "/sdcard/Pictures";

    private TaskManager taskManager;

    private Album currentAlbum;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final String url = getIntent().getStringExtra(EXTRA_URL);

        taskManager = new TaskManager(this, this);

        if (url != null) {
            if (getSupportFragmentManager().findFragmentByTag(TAG) == null) {
                final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                ft.add(android.R.id.content, AlbumsFragment.newInstance(url), TAG);
                ft.commit();
            }
        }
    }

    @Override
    public void onAlbumClick(int position, Album album, AdapterView<?> adapterView) {
        currentAlbum = album;
        openContextMenu(adapterView);
    }

    @Override
    public void onCreateMenu(Menu menu) {
        menu.add(Menu.NONE, MENU_LOAD_ALL, Menu.NONE, R.string.menu_load_all);
        menu.add(Menu.NONE, MENU_LOAD_ONE_BY_ONE, Menu.NONE, R.string.menu_load_one_by_one);
    }

    @Override
    public boolean onMenuItemSelected(MenuItem item) {
        String[] strs = currentAlbum.getId().split(":");
        File albumDir = new File(dir + File.separator + strs[strs.length - 1]);

        if (!albumDir.exists()) {
            if(albumDir.mkdir()) {
                if (BuildConfig.DEBUG)
                    Log.d(TAG, "Directory " + albumDir.getPath() + " created");
            } else {
                Log.e(TAG, "Directory does not created");
            }
        }
        switch (item.getItemId()) {
            case MENU_LOAD_ALL:
                if (BuildConfig.DEBUG)
                    Log.d(TAG, "Get and parse images entries");

                DownloadAndParseImagesTask task = new DownloadAndParseImagesTask(albumDir);
                task.execute(currentAlbum.getPhotosURL());
                return true;
            case MENU_LOAD_ONE_BY_ONE:
                Intent intent = new Intent(this, ImagesLoadActivity.class);
                intent.putExtra(ImagesLoadActivity.EXTRA_URL, currentAlbum.getPhotosURL());
                intent.putExtra(ImagesLoadActivity.ALBUM_DIR, albumDir.getPath());
                intent.putExtra(ImagesLoadActivity.ALBUM_CACHE, strs[strs.length - 1]);
                startActivity(intent);
                return true;
            default:
                return false;
        }
    }

    @Override
    public void onTaskComplete(LoadTask task) {
        if (task.isCancelled()) {
            Toast.makeText(this, R.string.task_canceled, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, R.string.task_completed, Toast.LENGTH_LONG).show();
        }
    }

    //Асинхронное выполнение запроса на фотки альбома
    private class DownloadAndParseImagesTask extends DownloadAndParseEntryTask<Image> {
        private File albumDir;

        private DownloadAndParseImagesTask(File albumDir) {
            this.albumDir = albumDir;
        }

        @Override
        public void onCompleteTask(List<Image> entries) {
            if (BuildConfig.DEBUG)
                Log.d(TAG, "start download images");

            taskManager.setupTask(new LoadTask(albumDir.getPath()), entries);
        }

        @Override
        public String getTag() {
            return TAG;
        }

        @Override
        public AbstractJsonEntryParser getJsonParser(String json) {
            return new JsonImagesParser(json);
        }
    }
}